#!/usr/bin/env python3
"""
LuaJIT MCP Server

面向软件：LuaJIT (Just-In-Time Compiler for Lua)

MCP tools 列表：
1. luajit_run_module - 执行 LuaJIT 脚本并加载模块
   用途：通过 -l 参数或 require 函数加载 Lua 模块并执行脚本
   参数：script_content (str): Lua 脚本内容, module_name (str): 模块名称, use_require (bool): 是否使用 require 方式
   返回：统一 JSON 结构

2. luajit_compile_bytecode - 编译 Lua 脚本为字节码文件
   用途：将 Lua 源代码编译为字节码并保存到指定文件
   参数：script_content (str): Lua 脚本内容, output_file (str): 输出字节码文件名
   返回：统一 JSON 结构

3. luajit_show_bytecode - 显示 Lua 脚本的字节码信息
   用途：编译 Lua 脚本并显示生成的字节码信息
   参数：script_content (str): Lua 脚本内容
   返回：统一 JSON 结构
"""

import subprocess
import tempfile
import os
from typing import Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("LuaJIT MCP Server")

@mcp.tool()
def luajit_run_module(script_content: str, module_name: str, use_require: bool = False) -> dict:
    """
    执行 LuaJIT 脚本并加载模块
    
    参数:
        script_content: Lua 脚本内容
        module_name: 要加载的模块名称
        use_require: 是否使用 require 方式加载模块 (False 时使用 -l 参数)
    
    返回:
        {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    with tempfile.NamedTemporaryFile(mode='w', suffix='.lua', delete=False) as f:
        f.write(script_content)
        script_file = f.name
    
    try:
        if use_require:
            # 使用 require 方式加载模块
            cmd = ["luajit", script_file]
        else:
            # 使用 -l 参数加载模块
            cmd = ["luajit", "-l", module_name, script_file]
        
        result = subprocess.run(cmd, capture_output=True, text=True, cwd="/tmp")
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    finally:
        os.unlink(script_file)

@mcp.tool()
def luajit_compile_bytecode(script_content: str, output_file: str) -> dict:
    """
    编译 Lua 脚本为字节码文件
    
    参数:
        script_content: Lua 脚本内容
        output_file: 输出字节码文件名
    
    返回:
        {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    with tempfile.NamedTemporaryFile(mode='w', suffix='.lua', delete=False) as f:
        f.write(script_content)
        script_file = f.name
    
    try:
        cmd = ["luajit", "-b", script_file, output_file]
        result = subprocess.run(cmd, capture_output=True, text=True, cwd="/tmp")
        
        # 检查输出文件是否生成且非空
        file_exists = os.path.exists(output_file) and os.path.getsize(output_file) > 0
        
        return {
            "success": result.returncode == 0 and file_exists,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    finally:
        os.unlink(script_file)

@mcp.tool()
def luajit_show_bytecode(script_content: str) -> dict:
    """
    显示 Lua 脚本的字节码信息
    
    参数:
        script_content: Lua 脚本内容
    
    返回:
        {
            "success": bool,
            "command": str,
            "exit_code": int,
            "stdout": str,
            "stderr": str
        }
    """
    with tempfile.NamedTemporaryFile(mode='w', suffix='.lua', delete=False) as f:
        f.write(script_content)
        script_file = f.name
    
    try:
        cmd = ["luajit", "-bl", script_file]
        result = subprocess.run(cmd, capture_output=True, text=True, cwd="/tmp")
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    finally:
        os.unlink(script_file)

if __name__ == "__main__":
    mcp.run()